import type {
    DaoCallback,
    DaoConfig,
    DaoItemCallback,
    DaoResultsCallback,
    DaoViewCallback,
    DataItem
} from "../types/tool/dao.types";
import {computed, type Ref, ref} from "vue";
import {Query} from "./query";
import {useMorghulisRequest} from "../hooks/request";
import type {Meta} from "../types/tool/meta.types.ts";
import {useMorghulisChannel} from "../hooks/channel.ts";
import type {MorghulisChannel} from "../types/tool/channel.types.ts";

/**
 * http和socket的loading冲突问题
 */

export function useDao(
    meta: Ref<Meta>, config?: DaoConfig
) {


    const {getHttpRequest} = useMorghulisRequest()
    const request = getHttpRequest(config?.auth)
    const handler = computed(() => `${meta.value.db}/${meta.value.entity}`)
    const root = computed(() => `data/${handler.value}`)
    const $loading = ref(true)
    const loading = computed(() => status.loading || $loading.value)

    function $exe(method: string, data: any, callback: (body: any | undefined) => void) {
        const url = `${root.value}/${method}`
        $loading.value = true
        request.post(url, data)
            .then(callback)
            .finally(() => $loading.value = false)
    }

    const {register, activate, status} = useMorghulisChannel(config?.auth)
    const channel: MorghulisChannel = {start: config?.start, stop: config?.stop, proceed: config?.proceed}
    register(handler.value, channel, `${root.value}/save_many`)


    return {
        save_one: (item: DataItem, cb: DaoItemCallback) => $exe('save_one', item, cb),
        delete_one: (id: string | number, cb: DaoCallback) => $exe('delete_one', {id}, cb),
        find_one: (id: string | number, cb: DaoItemCallback) => $exe('find_one', {id}, cb),
        delete_many: (query: Query, cb: DaoCallback) => $exe('delete_many', query, cb),
        update_many: (query: Query, template: DataItem, cb: DaoCallback) => $exe('update_many', {query, template}, cb),
        find_many: (query: Query, cb: DaoResultsCallback) => $exe('find_many', query, cb),
        save_many: (array: DataItem[]) => activate({db: meta.value.db, entity: meta.value.entity, array}),
        load_view: (cb: DaoViewCallback) => $exe('meta', {code: meta.value.code || 'default'}, cb),
        status,
        handler,
        loading
    }
}


// function defaultChannel(status: DaoStatus, config?: DaoConfig) {
//     const channel: MorghulisChannel = {
//         start: () => {
//             status.loading = true
//             status.ticker = {percentage: 0, index: '-', length: '-'}
//             config?.start && config.start()
//         },
//         stop: () => {
//             status.loading = false
//             status.ticker = null
//             config?.stop && config.stop()
//         },
//         proceed: (payload) => {
//             status.loading = true
//             status.ticker = payload
//             config?.proceed && config.proceed(payload)
//         }
//     }
//     return channel
// }
